package com.jsoft.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.jsoft.annotation.Repeat;
import com.jsoft.configuration.CustomObjectMapper;
import com.jsoft.constant.Constants;
import com.jsoft.core.RedisTemplate;
import com.jsoft.util.Result;
import org.springframework.util.DigestUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Date;



/**
 * 表单重复提交拦截器
 */
public class RepeatInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CustomObjectMapper objectMapper;

    /**
     * 检查表单是否重复提交
     *
     * @return 返回是否提交
     */
    public boolean isSubmit(HttpServletRequest request, Repeat repeat) throws IOException {

        //获取用户名
        String username = request.getHeader((Constants.HEADER_USERNAME));
        //获取请求地址
        String url = request.getRequestURI();
        if(username == null){
            return false;
        }

        String key = Constants.REPEAT_PREFIX + username + "" +url;//格式-》用户名:url
        //获取redis中的对应的表单数据
        String result = redisTemplate.get(key);
        //如果存在且他们相同
        if (result != null && username.equals(result)) {
            return true;
        } else {
            //否则存入redis
            redisTemplate.set(key, username, repeat.value());
            return false;
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取方法信息
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查方法上的注解
        Repeat annotation = method.getAnnotation(Repeat.class);
        if (annotation != null) {
            if (isSubmit(request, annotation)) {
                Result result = Result.error("您重复提交次数过多");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(result));
                return false;
            }
        }
        return true;
    }
}
